<template>
  <a-table :columns="columns" :data-source="dataSource" bordered :pagination="false">
    <template #bodyCell="{ column, text, record }">
      <template
        v-if="['in1', 'in2', 'th1Max', 'th2Max', 'th1Min', 'th2Min'].includes(column.dataIndex)"
      >
        <div>
          <a-input
            v-if="editableData[record.key]"
            v-model:value="editableData[record.key][column.dataIndex]"
            style="margin: -5px 0"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
    </template>
  </a-table>
</template>
  <script lang="ts">
import { cloneDeep } from 'lodash-es';
import { defineComponent, reactive, ref } from 'vue';
import type { UnwrapRef } from 'vue';

const columns = [
  {
    title: '监测点',
    dataIndex: 'name',
    width: '25%',
  },
  {
    title: '通道',
    dataIndex: 'channel',
    width: '10%',
  },
  {
    title: '初始值1',
    dataIndex: 'in1',
  },
  {
    title: '预警上限1',
    dataIndex: 'th1Max',
  },
  {
    title: '预警下限1',
    dataIndex: 'th1Min',
  },
  {
    title: '初始值2',
    dataIndex: 'in2',
  },
  {
    title: '预警上限2',
    dataIndex: 'th2Max',
  },
  {
    title: '预警下限2',
    dataIndex: 'th2Min',
  },
];

interface DataItem {
  key: string;
  name: string;
  channel: number;
  in1: number;
  in2: number;
  th1Min: number;
  th2Min: number;
  th1Max: number;
  th2Max: number;
}

export default defineComponent({
  setup() {
    const dataSource = ref([]);
    const editableData: UnwrapRef<Record<string, DataItem>> = reactive({});

    function init(rows) {
      dataSource.value = rows.map((item) => {
        return {
          key: '' + item.id,
          name: '传感器' + item.id,
          channel: item.channel,
          in1: item.in1,
          in2: item.in2,
          th1Min: item.th1Min,
          th2Min: item.th2Min,
          th1Max: item.th1Max,
          th2Max: item.th2Max,
        };
      });
      dataSource.value.forEach((row) => {
        editableData[row.key] = cloneDeep(row);
      });
    }

    const save = () => {
      dataSource.value.forEach((row, index) => {
        let key = row.key;
        Object.assign(dataSource.value[index], editableData[key]);
        // delete editableData[key];
      });
      // Object.assign(dataSource.value.filter((item) => key === item.key)[0], editableData[key]);
    };

    const cancel = () => {
      // Object.keys(editableData).map((key) => {
      //   delete editableData[key];
      // });
    };

    return {
      dataSource,
      columns,
      editableData,
      save,
      cancel,
      init,
    };
  },
});
</script>
  <style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
</style>
  